<template>
  <a-modal
    :visible="visible"
    :title="title"
    :mask-closable="false"
    :width="800"
    @ok="handleSubmit"
    @cancel="handleCancel"
  >
    <a-form
      ref="formRef"
      :model="formData"
      :rules="rules"
      layout="vertical"
    >
      <a-row :gutter="16">
        <a-col :span="12">
          <a-form-item field="username" label="用户名" validate-trigger="blur">
            <a-input v-model="formData.username" placeholder="请输入用户名" allow-clear />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item field="name" label="姓名" validate-trigger="blur">
            <a-input v-model="formData.name" placeholder="请输入姓名" allow-clear />
          </a-form-item>
        </a-col>
      </a-row>

      <a-row :gutter="16">
        <a-col :span="12">
          <a-form-item field="gender" label="性别">
            <a-radio-group v-model="formData.gender">
              <a-radio :value="1">男</a-radio>
              <a-radio :value="2">女</a-radio>
            </a-radio-group>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item field="phone" label="手机号" validate-trigger="blur">
            <a-input v-model="formData.phone" placeholder="请输入手机号" allow-clear />
          </a-form-item>
        </a-col>
      </a-row>

      <a-row :gutter="16">
        <a-col :span="12">
          <a-form-item field="position" label="职位">
            <a-select v-model="formData.position" placeholder="请选择职位">
              <a-option :value="1">班主任</a-option>
              <a-option :value="2">讲师</a-option>
              <a-option :value="3">学工主管</a-option>
              <a-option :value="4">教研主管</a-option>
              <a-option :value="5">咨询师</a-option>
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item field="deptId" label="部门">
            <a-select v-model="formData.deptId" placeholder="请选择部门">
              <a-option v-for="dept in deptList" :key="dept.id" :value="dept.id">
                {{ dept.name }}
              </a-option>
            </a-select>
          </a-form-item>
        </a-col>
      </a-row>

      <a-row :gutter="16">
        <a-col :span="12">
          <a-form-item field="salary" label="薪资">
            <a-input-number
              v-model="formData.salary"
              placeholder="请输入薪资"
              :min="0"
              :step="1000"
              :precision="2"
              style="width: 100%"
            />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item field="hireDate" label="入职日期">
            <a-date-picker
              v-model="formData.hireDate"
              style="width: 100%"
            />
          </a-form-item>
        </a-col>
      </a-row>

      <a-form-item field="image" label="头像">
        <a-upload
          :file-list="[]"
          :show-file-list="false"
          accept="image/*"
          :custom-request="handleUpload"
          :before-upload="beforeUpload"
        >
          <template #upload-button>
            <div class="avatar-upload-wrapper">
              <div class="avatar-upload-trigger">
                <template v-if="formData.image">
                  <img :src="formData.image" />
                  <div class="avatar-upload-mask">
                    <icon-edit />
                    <div class="avatar-upload-text">更换头像</div>
                  </div>
                </template>
                <template v-else>
                  <div class="avatar-upload-placeholder">
                    <icon-plus />
                    <div class="avatar-upload-text">上传头像</div>
                  </div>
                </template>
              </div>
            </div>
          </template>
        </a-upload>
      </a-form-item>

      <!-- 工作经历 -->
      <a-form-item>
        <template #label>
          <div class="expr-header">
            <span>工作经历</span>
            <a-button type="outline" size="mini" @click="addExpr">
              <template #icon><icon-plus /></template>
              添加工作经历
            </a-button>
          </div>
        </template>
        <div class="expr-list">
          <div v-for="(expr, index) in formData.exprList" :key="index" class="expr-item">
            <div class="expr-item-header">
              <span>工作经历 {{ index + 1 }}</span>
              <a-button
                type="text"
                status="danger"
                size="mini"
                @click="removeExpr(index)"
              >
                <template #icon><icon-delete /></template>
                删除
              </a-button>
            </div>
            <a-row :gutter="16">
              <a-col :span="8">
                <a-form-item
                  :field="`exprList[${index}].company`"
                  label="公司名称"
                  validate-trigger="blur"
                >
                  <a-input
                    v-model="expr.company"
                    placeholder="请输入公司名称"
                    allow-clear
                  />
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item
                  :field="`exprList[${index}].position`"
                  label="职位"
                  validate-trigger="blur"
                >
                  <a-input
                    v-model="expr.position"
                    placeholder="请输入职位"
                    allow-clear
                  />
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item
                  :field="`exprList[${index}].dateRange`"
                  label="起止时间"
                >
                  <a-range-picker
                    v-model="expr.dateRange"
                    style="width: 100%"
                    @change="handleExprDateChange(expr)"
                  />
                </a-form-item>
              </a-col>
            </a-row>
          </div>
        </div>
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<script lang="ts" setup>
import { computed, onMounted, reactive, ref, watch } from 'vue'
import { Message } from '@arco-design/web-vue'
import dayjs from 'dayjs'
import type { UploadRequestOption as RequestOption } from '@arco-design/web-vue'
import type { Employee, Experience } from '@/apis/system/emp'
import { addEmp, getEmpById, updateEmp } from '@/apis/system/emp'
import type { DeptItem } from '@/apis/system/dept'
import { getDeptList } from '@/apis/system/dept'
import { uploadFile } from '@/apis/system/upload'

const props = withDefaults(defineProps<{
  visible: boolean
  title: string
  empData?: Employee
}>(), {
  visible: false,
  title: '',
  empData: undefined
})

const emit = defineEmits<{
  (e: 'update:visible', visible: boolean): void
  (e: 'success'): void
}>()

// 表单数据
const formRef = ref()
const formData = reactive<Employee & { exprList: (Experience & { dateRange?: [Date, Date] })[] }>({
  username: '',
  name: '',
  gender: 1,
  image: '',
  position: undefined as any,
  salary: undefined as any,
  hireDate: '',
  deptId: undefined as any,
  phone: '',
  exprList: []
})

// 表单校验规则
const rules = {
  'username': [
    { required: true, message: '请输入用户名' },
    { minLength: 2, maxLength: 20, message: '用户名长度为2-20个字符' },
    { match: /^[a-z0-9]+$/i, message: '用户名只能包含字母和数字' }
  ],
  'name': [
    { required: true, message: '请输入姓名' },
    { minLength: 2, maxLength: 10, message: '姓名长度为2-10个字符' },
    { match: /^[\u4E00-\u9FA5]+$/, message: '姓名只能包含汉字' }
  ],
  'gender': [
    { required: true, message: '请选择性别' }
  ],
  'phone': [
    { required: true, message: '请输入手机号' },
    { match: /^1[3-9]\d{9}$/, message: '请输入正确的11位手机号' }
  ],
  'position': [
    { required: false, message: '请选择职位' }
  ],
  'salary': [
    { required: false, message: '请输入薪资' },
    { type: 'number', message: '薪资必须为数字' }
  ],
  'image': [
    { required: false, message: '请上传头像' }
  ],
  'hireDate': [
    { required: false, message: '请选择入职日期' }
  ],
  'deptId': [
    { required: false, message: '请选择部门' }
  ],
  'exprList.*.company': [
    { required: true, message: '请输入公司名称' },
    { minLength: 2, maxLength: 50, message: '公司名称长度为2-50个字符' },
    { match: /^[\u4E00-\u9FA5a-z0-9]+$/i, message: '公司名称只能包含汉字、字母和数字' }
  ],
  'exprList.*.position': [
    { required: true, message: '请输入职位' },
    { minLength: 2, maxLength: 50, message: '职位长度为2-50个字符' },
    { match: /^[\u4E00-\u9FA5a-z0-9]+$/i, message: '职位只能包含汉字、字母和数字' }
  ],
  'exprList.*.dateRange': [
    { required: true, message: '请选择起止时间' }
  ]
}

// 部门列表
const deptList = ref<DeptItem[]>([])

// 获取部门列表
const fetchDeptList = async () => {
  try {
    const res = await getDeptList()
    if (res.code === 1) {
      deptList.value = res.data
    }
  } catch (error) {
    console.error('获取部门列表失败:', error)
  }
}

// 监听编辑数据变化
watch(
  () => props.empData,
  async (emp) => {
    if (emp?.id) {
      // 编辑时获取完整数据
      const res = await getEmpById(emp.id)
      if (res.code === 1) {
        const data = res.data
        // 重置表单数据
        Object.assign(formData, {
          id: data.id,
          username: data.username,
          name: data.name,
          gender: data.gender,
          image: data.image, // 确保设置图片
          position: data.position,
          salary: data.salary,
          hireDate: data.hireDate,
          deptId: data.deptId,
          phone: data.phone,
          exprList: data.exprList?.map((item) => ({
            ...item,
            dateRange: item.startDate && item.endDate
              ? [
                  dayjs(item.startDate).toDate(),
                  dayjs(item.endDate).toDate()
                ]
              : undefined
          })) || []
        })
      }
    } else {
      // 新增时重置表单
      Object.assign(formData, {
        id: undefined,
        username: '',
        name: '',
        gender: 1,
        image: '', // 清空图片
        position: undefined,
        salary: undefined,
        hireDate: '',
        deptId: undefined,
        phone: '',
        exprList: []
      })
    }
  },
  { immediate: true }
)

// 添加工作经历
const addExpr = () => {
  formData.exprList.push({
    company: '',
    position: '',
    startDate: '',
    endDate: '',
    dateRange: undefined
  })
}

// 移除工作经历
const removeExpr = (index: number) => {
  formData.exprList.splice(index, 1)
}

// 工作经历日期改变
const handleExprDateChange = (expr: Experience & { dateRange?: [Date, Date] }) => {
  if (expr.dateRange) {
    expr.startDate = dayjs(expr.dateRange[0]).format('YYYY-MM-DD')
    expr.endDate = dayjs(expr.dateRange[1]).format('YYYY-MM-DD')
  } else {
    expr.startDate = ''
    expr.endDate = ''
  }
}

// 上传头像前校验
const beforeUpload = (file: File) => {
  const isImage = /^image\//.test(file.type)
  if (!isImage) {
    Message.error('只能上传图片文件!')
    return false
  }
  const isLt2M = file.size / 1024 / 1024 < 2
  if (!isLt2M) {
    Message.error('图片大小不能超过 2MB!')
    return false
  }
  return true
}

// 处理头像上传
const handleUpload = async (option: RequestOption) => {
  const { onProgress, onError, onSuccess, fileItem } = option

  try {
    if (!fileItem) {
      throw new Error('上传文件不能为空')
    }

    const uploadFormData = new FormData()
    uploadFormData.append('file', fileItem.file)

    onProgress(0)
    const res = await uploadFile(fileItem.file)
    onProgress(100)

    if (res.code === 1) {
      // 直接更新表单数据中的 image 字段
      formData.image = res.data
      onSuccess(res.data)
      Message.success('上传成功')
    } else {
      throw new Error(res.message || '上传失败')
    }
  } catch (error) {
    onError(error as Error)
    Message.error((error as Error).message || '上传失败')
  }
}

// 提交表单
const handleSubmit = async () => {
  try {
    // 表单校验
    const errors = await formRef.value?.validate()
    if (errors) {
      return // 如果有错误，直接返回，不调用后端接口
    }

    // 校验通过后，构造提交数据
    const submitData = {
      ...formData,
      // 处理日期格式
      hireDate: dayjs(formData.hireDate).format('YYYY-MM-DD'),
      // 处理工作经历数据
      exprList: formData.exprList
        .filter((expr) => expr.company && expr.position && expr.startDate && expr.endDate)
        .map(({ dateRange, ...expr }) => ({
          ...expr,
          // 如果是编辑状态，需要保留 id 和 empId
          id: expr.id,
          empId: formData.id,
          // 确保日期格式正确
          startDate: expr.startDate,
          endDate: expr.endDate
        }))
    }

    // 移除不需要的字段
    delete (submitData as any).dateRange

    // 调用后端接口
    const api = submitData.id ? updateEmp : addEmp
    const res = await api(submitData)
    if (res.code === 1) {
      Message.success(`${submitData.id ? '修改' : '添加'}成功`)
      emit('update:visible', false)
      emit('success')
    }
  } catch (error) {
    console.error('保存失败:', error)
  }
}

// 取消
const handleCancel = () => {
  formRef.value?.resetFields()
  emit('update:visible', false)
}

// 页面加载时获取部门列表
onMounted(() => {
  fetchDeptList()
})
</script>

<style scoped lang="less">
.expr-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
}

.expr-list {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.expr-item {
  padding: 16px;
  border: 1px dashed var(--color-border);
  border-radius: 4px;
  background-color: var(--color-fill-2);

  .expr-item-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 16px;
    padding-bottom: 8px;
    border-bottom: 1px dashed var(--color-border);

    span {
      font-weight: 500;
      color: var(--color-text-1);
    }
  }

  :deep(.arco-form-item) {
    margin-bottom: 0;
  }
}

.avatar-upload-wrapper {
  width: 100px;
  height: 100px;
  cursor: pointer;
}

.avatar-upload-trigger {
  width: 100%;
  height: 100%;
  border: 1px dashed var(--color-border);
  border-radius: 50%;
  overflow: hidden;
  transition: border-color 0.1s;
  position: relative;

  &:hover {
    border-color: rgb(var(--primary-6));
  }

  img {
    width: 100%;
    height: 100%;
    object-fit: cover;
  }
}

.avatar-upload-placeholder {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
  color: var(--color-text-3);
}

.avatar-upload-mask {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  color: #fff;
  background: rgba(0, 0, 0, 0.6);
  opacity: 0;
  transition: opacity 0.1s;

  &:hover {
    opacity: 1;
  }
}

.avatar-upload-text {
  margin-top: 8px;
  font-size: 12px;
}
</style>
